package com.aerozhonghuan.logisticsmall.modules.common;//package com.mapbar.android.obd.view.common;

import android.Manifest;
import android.content.Intent;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.Window;
import android.view.WindowManager;
import android.widget.Toast;

import com.aerozhonghuan.foundation.base.SingleActivity;
import com.aerozhonghuan.foundation.eventbus.EventBusManager;
import com.aerozhonghuan.foundation.log.LogUtil;
import com.aerozhonghuan.logisticsmall.BuildConfig;
import com.aerozhonghuan.logisticsmall.R;
import com.aerozhonghuan.logisticsmall.modules.common.entity.CommonConstants;
import com.aerozhonghuan.logisticsmall.modules.user.beans.UserBean;
import com.aerozhonghuan.logisticsmall.modules.user.beans.UserInfo;
import com.aerozhonghuan.logisticsmall.modules.user.logic.LoginLogic;
import com.aerozhonghuan.logisticsmall.modules.user.logic.UserInfoManager;
import com.aerozhonghuan.logisticsmall.utils.EnvironmentInfoUtils;
import com.aerozhonghuan.logisticsmall.utils.NetUtils;
import com.aerozhonghuan.logisticsmall.utils.PhoneUtils;
import com.aerozhonghuan.logisticsmall.utils.WindowUtil;
import com.aerozhonghuan.logisticsmall.utils.permisson.PermissionCheckUtils;
import com.aerozhonghuan.logisticsmall.utils.permisson.PermissionEvent;
import com.aerozhonghuan.oknet2.CommonCallback;
import com.aerozhonghuan.oknet2.CommonMessage;

import org.greenrobot.eventbus.Subscribe;


/**
 * An example full-screen activity that shows and hides the system UI (i.e.
 * status bar and navigation/system bar) with user interaction.
 */
public class SplashActivity extends SingleActivity {
    private static final String TAG = "SplashActivity";
    private static final int MY_PERMISSIONS_REQUEST_STORAGE = 111;
    private Handler mHandler;
    private String checkPermission[] = {Manifest.permission.ACCESS_FINE_LOCATION,
            Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.READ_PHONE_STATE};

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        this.requestWindowFeature(Window.FEATURE_NO_TITLE);
        // 取消状态栏
        this.getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);
        WindowManager.LayoutParams params = this.getWindow().getAttributes();
        params.systemUiVisibility = View.SYSTEM_UI_FLAG_LOW_PROFILE;
        this.getWindow().setAttributes(params);
        setContentView(R.layout.splash_view);
        EventBusManager.register(this);
        mHandler = new Handler();
        checkMyAppPermission();
    }

    private void checkMyAppPermission() {
        if (PermissionCheckUtils.checkPerissonIntent(this, checkPermission)) {
            initApp();
        }
    }

    @Subscribe
    public void onPushMsgEvent(PermissionEvent event) {
        boolean isCheckPermission = event.isCheckPemission();
        if (isCheckPermission) {
            initApp();
        }
    }

    private void initApp() {
        //打印环境变量信息
        if (BuildConfig.DEBUG) {
            new EnvironmentInfoUtils().print(this);
        }
        if (!NetUtils.isConnected(this)) {
            Toast.makeText(this, "网络异常, 请联网后重试", Toast.LENGTH_SHORT).show();
        }
        // 判断是否有devId, 如果没有先调用提交接口获取devId
        if (UserInfoManager.isHaveDeviceId()) {
            final String devId = UserInfoManager.getDeviceId();
            // 判断是否有uuid, 如果没有调用更新devId接口,获取uuid
            if (UserInfoManager.isHaveUuid()) {
                checkToken(devId, UserInfoManager.getUuid());
            } else {
                LoginLogic.updateDevice(this, UserInfoManager.getDeviceId(), new LoginLogic.OnUpdateDeviceCallback() {
                    @Override
                    public void onSuccess(String uuid) {
                        checkToken(devId, uuid);
                    }

                    @Override
                    public void onFailure() {
                        Toast.makeText(SplashActivity.this, "数据异常", Toast.LENGTH_SHORT).show();
                        LogUtil.d(TAG, "uuid异常");
                    }
                });
            }
        } else {
            String devName = PhoneUtils.getPhoneName();
            String devResolution = WindowUtil.getWindowResolution(this);
            String devOs = "Android";
            String devOsVersion = Build.VERSION.RELEASE;
            String devDetails = PhoneUtils.getImei(this);
            LoginLogic.pushDevice(this, devName, devResolution, devOs, devOsVersion, devDetails, new LoginLogic.OnPushDeviceCallback() {
                @Override
                public void onSuccess(String devId, String uuid) {
                    checkToken(devId, uuid);
                }

                @Override
                public void onFailure() {
                    Toast.makeText(SplashActivity.this, "数据异常", Toast.LENGTH_SHORT).show();
                    LogUtil.d(TAG, "获取deviceid,uuid异常");
                }
            });
        }
    }

    /**
     * 获取devId和uuid后检测token,检测token后看是否登录
     *
     * @param devId
     * @param uuid
     */
    private void checkToken(String devId, String uuid) {
        UserInfo userInfo = UserInfoManager.getCurrentUserBaseInfo();
        String token = "";
        if (userInfo != null) {
            token = userInfo.getToken();
        }
        LoginLogic.checkToken(this, null, token, devId, uuid, new LoginLogic.OnCheckTokenCallback() {
            @Override
            public void onSuccess(UserInfo userInfo) {
                if (userInfo.isLogin()) {
                    updateUserInfo();
                } else {
                    goPage_Login();
                    finish();
                }
            }

            @Override
            public void onFailure() {
                Toast.makeText(SplashActivity.this, "数据异常", Toast.LENGTH_SHORT).show();
            }
        });
    }

    /**
     * 获取用户信息后进入首页
     */
    private void updateUserInfo() {
        LoginLogic.getUserInfo(this, new CommonCallback<UserBean>() {
            @Override
            public void onSuccess(UserBean userBean, CommonMessage commonMessage, String allResponseString) {
                if (userBean != null) {
                    UserInfoManager.saveUserDetailInfo(userBean);
                    goPage_MainActivity();
                    finish();
                } else {
                    goPage_Login();
                    finish();
                }
            }

            @Override
            public boolean onFailure(int httpCode, Exception exception, CommonMessage responseMessage, String allResponseString) {
                goPage_Login();
                finish();
                return true;
            }
        });
    }

    private void goPage_MainActivity() {
        Intent intent = ActivityDispatcher.getIntent_MainActivity(getContext());
        intent.putExtra("IS_FIRST", true);
        intent.putExtra(CommonConstants.IS_FROM_SPLASH_MAIN, true);
        if (getIntent() != null && getIntent().getExtras() != null && getIntent().getExtras().containsKey("notify_intent")) {
            intent.putExtra("notify_intent", getIntent().getParcelableExtra("notify_intent"));
        }
        startActivity(intent);
        //阻止任何动画
        overridePendingTransition(0, 0);
    }

    private void goPage_Login() {
        Intent intent = ActivityDispatcher.getIntent_LoginOnLogout(getContext());
        intent.putExtra(CommonConstants.IS_FROM_SPLASH_LOGIN, true);
        startActivity(intent);
    }

    @Override
    protected void onDestroy() {
        mHandler = null;
        EventBusManager.unregister(this);
        super.onDestroy();
    }
}
